{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "826IBSWMN4rr"
      },
      "source": [
        "**Copyright 2020 The TensorFlow Authors.**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "colab": {},
        "colab_type": "code",
        "id": "ITj3u97-tNR7"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "BYwfpc4wN4rt"
      },
      "source": [
        "# Weight clustering comprehensive guide"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "IFva_Ed5N4ru"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/model_optimization/guide/clustering/clustering_comprehensive_guide\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/model-optimization/blob/master/tensorflow_model_optimization/g3doc/guide/clustering/clustering_comprehensive_guide.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/model-optimization/blob/master/tensorflow_model_optimization/g3doc/guide/clustering/clustering_comprehensive_guide.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/model-optimization/tensorflow_model_optimization/g3doc/guide/clustering/clustering_comprehensive_guide.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "tidmcl3sN4rv"
      },
      "source": [
        "Welcome to the comprehensive guide for *weight clustering*, part of the TensorFlow Model Optimization toolkit.\n",
        "\n",
        "This page documents various use cases and shows how to use the API for each one. Once you know which APIs you need, find the parameters and the low-level details in the [API docs](https://www.tensorflow.org/model_optimization/api_docs/python/tfmot/clustering):\n",
        "\n",
        "* If you want to see the benefits of weight clustering and what's supported, check the [overview](https://www.tensorflow.org/model_optimization/guide/clustering).\n",
        "* For a single end-to-end example, see the [weight clustering example](https://www.tensorflow.org/model_optimization/guide/clustering/clustering_example).\n",
        "\n",
        "In this guide, the following use cases are covered:\n",
        "* Define a clustered model.\n",
        "* Checkpoint and deserialize a clustered model.\n",
        "* Improve the accuracy of the clustered model.\n",
        "* For deployment only, you must take steps to see compression benefits.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "RRtKxbo8N4rv"
      },
      "source": [
        "## Setup\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "08dJRvOqN4rw",
        "scrolled": true
      },
      "outputs": [],
      "source": [
        "! pip install -q tensorflow-model-optimization\n",
        "\n",
        "import tensorflow as tf\n",
        "import numpy as np\n",
        "import tempfile\n",
        "import os\n",
        "import tensorflow_model_optimization as tfmot\n",
        "\n",
        "input_dim = 20\n",
        "output_dim = 20\n",
        "x_train = np.random.randn(1, input_dim).astype(np.float32)\n",
        "y_train = tf.keras.utils.to_categorical(np.random.randn(1), num_classes=output_dim)\n",
        "\n",
        "def setup_model():\n",
        "  model = tf.keras.Sequential([\n",
        "      tf.keras.layers.Dense(input_dim, input_shape=[input_dim]),\n",
        "      tf.keras.layers.Flatten()\n",
        "  ])\n",
        "  return model\n",
        "\n",
        "def train_model(model):\n",
        "  model.compile(\n",
        "      loss=tf.keras.losses.categorical_crossentropy,\n",
        "      optimizer='adam',\n",
        "      metrics=['accuracy']\n",
        "  )\n",
        "  model.summary()\n",
        "  model.fit(x_train, y_train)\n",
        "  return model\n",
        "\n",
        "def save_model_weights(model):\n",
        "  _, pretrained_weights = tempfile.mkstemp('.h5')\n",
        "  model.save_weights(pretrained_weights)\n",
        "  return pretrained_weights\n",
        "\n",
        "def setup_pretrained_weights():\n",
        "  model= setup_model()\n",
        "  model = train_model(model)\n",
        "  pretrained_weights = save_model_weights(model)\n",
        "  return pretrained_weights\n",
        "\n",
        "def setup_pretrained_model():\n",
        "  model = setup_model()\n",
        "  pretrained_weights = setup_pretrained_weights()\n",
        "  model.load_weights(pretrained_weights)\n",
        "  return model\n",
        "\n",
        "def save_model_file(model):\n",
        "  _, keras_file = tempfile.mkstemp('.h5') \n",
        "  model.save(keras_file, include_optimizer=False)\n",
        "  return keras_file\n",
        "\n",
        "def get_gzipped_model_size(model):\n",
        "  # It returns the size of the gzipped model in bytes.\n",
        "  import os\n",
        "  import zipfile\n",
        "\n",
        "  keras_file = save_model_file(model)\n",
        "\n",
        "  _, zipped_file = tempfile.mkstemp('.zip')\n",
        "  with zipfile.ZipFile(zipped_file, 'w', compression=zipfile.ZIP_DEFLATED) as f:\n",
        "    f.write(keras_file)\n",
        "  return os.path.getsize(zipped_file)\n",
        "\n",
        "setup_model()\n",
        "pretrained_weights = setup_pretrained_weights()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "ARd37qONN4rz"
      },
      "source": [
        "# Define a clustered model\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "zHB3pkU3N4r0"
      },
      "source": [
        "### Cluster a whole model (sequential and functional)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "ig-il1lmN4r1"
      },
      "source": [
        "**Tips** for better model accuracy:\n",
        "\n",
        "* You must pass a pre-trained model with acceptable accuracy to this API. Training models from scratch with clustering results in subpar accuracy. \n",
        "* In some cases, clustering certain layers has a detrimental effect on model accuracy. Check \"Cluster some layers\" to see how to skip clustering the layers that affect accuracy the most.\n",
        "\n",
        "To cluster all layers, apply `tfmot.clustering.keras.cluster_weights` to the model.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "29g7OADjN4r1",
        "scrolled": true
      },
      "outputs": [],
      "source": [
        "import tensorflow_model_optimization as tfmot\n",
        "\n",
        "cluster_weights = tfmot.clustering.keras.cluster_weights\n",
        "CentroidInitialization = tfmot.clustering.keras.CentroidInitialization\n",
        "\n",
        "clustering_params = {\n",
        "  'number_of_clusters': 3,\n",
        "  'cluster_centroids_init': CentroidInitialization.DENSITY_BASED\n",
        "}\n",
        "\n",
        "model = setup_model()\n",
        "model.load_weights(pretrained_weights)\n",
        "\n",
        "clustered_model = cluster_weights(model, **clustering_params)\n",
        "\n",
        "clustered_model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "zEOHK4OON4r7"
      },
      "source": [
        "### Cluster some layers (sequential and functional models)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "ENscQ7ZWN4r8"
      },
      "source": [
        "**Tips** for better model accuracy:\n",
        "\n",
        "* You must pass a pre-trained model with acceptable accuracy to this API. Training models from scratch with clustering results in subpar accuracy.\n",
        "* Cluster later layers with more redundant parameters (e.g. `tf.keras.layers.Dense`, `tf.keras.layers.Conv2D`), as opposed to the early layers.\n",
        "* Freeze early layers prior to the clustered layers during fine-tuning. Treat the number of frozen layers as a hyperparameter. Empirically, freezing most early layers is ideal for the current clustering API.\n",
        "* Avoid clustering critical layers (e.g. attention mechanism).\n",
        "\n",
        "**More**: the `tfmot.clustering.keras.cluster_weights` API docs provide details on how to vary the clustering configuration per layer."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "IqBdl3uJN4r_",
        "scrolled": true
      },
      "outputs": [],
      "source": [
        "# Create a base model\n",
        "base_model = setup_model()\n",
        "base_model.load_weights(pretrained_weights)\n",
        "\n",
        "# Helper function uses `cluster_weights` to make only \n",
        "# the Dense layers train with clustering\n",
        "def apply_clustering_to_dense(layer):\n",
        "  if isinstance(layer, tf.keras.layers.Dense):\n",
        "    return cluster_weights(layer, **clustering_params)\n",
        "  return layer\n",
        "\n",
        "# Use `tf.keras.models.clone_model` to apply `apply_clustering_to_dense` \n",
        "# to the layers of the model.\n",
        "clustered_model = tf.keras.models.clone_model(\n",
        "    base_model,\n",
        "    clone_function=apply_clustering_to_dense,\n",
        ")\n",
        "\n",
        "clustered_model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "hN0DgpvD5Add"
      },
      "source": [
        "# Checkpoint and deserialize a clustered model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "hfji5KWN6XCF"
      },
      "source": [
        "**Your use case:** this code is only needed for the HDF5 model format (not HDF5 weights or other formats)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "w7P67mPk6RkQ"
      },
      "outputs": [],
      "source": [
        "# Define the model.\n",
        "base_model = setup_model()\n",
        "base_model.load_weights(pretrained_weights)\n",
        "clustered_model = cluster_weights(base_model, **clustering_params)\n",
        "\n",
        "# Save or checkpoint the model.\n",
        "_, keras_model_file = tempfile.mkstemp('.h5')\n",
        "clustered_model.save(keras_model_file, include_optimizer=True)\n",
        "\n",
        "# `cluster_scope` is needed for deserializing HDF5 models.\n",
        "with tfmot.clustering.keras.cluster_scope():\n",
        "  loaded_model = tf.keras.models.load_model(keras_model_file)\n",
        "\n",
        "loaded_model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "cUv-scK-N4sN"
      },
      "source": [
        "# Improve the accuracy of the clustered model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "-fZZopDBN4sO"
      },
      "source": [
        "For your specific use case, there are tips you can consider:\n",
        "\n",
        "* Centroid initialization plays a key role in the final optimized model accuracy. In general, linear initialization outperforms density and random initialization since it does not tend to miss large weights. However, density initialization has been observed to give better accuracy for the case of using very few clusters on weights with bimodal distributions.\n",
        "\n",
        "* Set a learning rate that is lower than the one used in training when fine-tuning the clustered model.\n",
        "\n",
        "* For general ideas to improve model accuracy, look for tips for your use case(s) under \"Define a clustered model\"."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "4DXw7YbyN4sP"
      },
      "source": [
        "# Deployment"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "5Y5zLfPzN4sQ"
      },
      "source": [
        "## Export model with size compression"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "wX4OrHD9N4sQ"
      },
      "source": [
        "**Common mistake**: both `strip_clustering` and applying a standard compression algorithm (e.g. via gzip) are necessary to see the compression benefits of clustering."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "ZvuiCBsVN4sR"
      },
      "outputs": [],
      "source": [
        "model = setup_model()\n",
        "clustered_model = cluster_weights(model, **clustering_params)\n",
        "\n",
        "clustered_model.compile(\n",
        "    loss=tf.keras.losses.categorical_crossentropy,\n",
        "    optimizer='adam',\n",
        "    metrics=['accuracy']\n",
        ")\n",
        "\n",
        "clustered_model.fit(\n",
        "    x_train,\n",
        "    y_train\n",
        ")\n",
        "\n",
        "final_model = tfmot.clustering.keras.strip_clustering(clustered_model)\n",
        "\n",
        "print(\"final model\")\n",
        "final_model.summary()\n",
        "\n",
        "print(\"\\n\")\n",
        "print(\"Size of gzipped clustered model without stripping: %.2f bytes\" \n",
        "      % (get_gzipped_model_size(clustered_model)))\n",
        "print(\"Size of gzipped clustered model with stripping: %.2f bytes\" \n",
        "      % (get_gzipped_model_size(final_model)))"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "clustering_comprehensive_guide.ipynb",
      "private_outputs": true,
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
